package yxy.apple.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;

public class GetIpAndPort {
//	// 获取ip
	public static String getLocalIP() {
		String localIP = "127.0.0.1";
		try {
			for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
				NetworkInterface networkInterface = interfaces.nextElement();
				if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
					continue;
				}
				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress address = addresses.nextElement();
					if (address instanceof Inet4Address) {
						localIP = address.getHostAddress();
						return localIP;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return localIP;
	}

	// 获取内网ip
//	public static String getLocalIp() {
//		try {
//			for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
//				NetworkInterface networkInterface = interfaces.nextElement();
//				if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
//					continue;
//				}
//				Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
//				if (addresses.hasMoreElements()) {
//					return addresses.nextElement().getHostAddress();
//				}
//			}
//		} catch (SocketException e) {
//		}
//		return null;
//	}

	// 获取端口
	public static String getLocalPort() {
		try {
			MBeanServer server;
			if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
				server = MBeanServerFactory.findMBeanServer(null).get(0);
			} else {
				return "";
			}
			Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
					Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

			Iterator<ObjectName> iterator = names.iterator();
			if (iterator.hasNext()) {
				ObjectName name = iterator.next();
				return server.getAttribute(name, "port").toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getIpAndPort() {
		return getLocalIP() + ":" + getLocalPort();
	}

}
